import React, {useEffect, useState} from "react"
import {
    createMarketSaleDocument,
    getMarketSaleDocumentDetailByMonth, MarketSaleDocumentDetail, moveItemsToAnotherDocument
} from "../../apis/MarketSaleDocumentApi";
import ArrayUtils from "@zxy-cn/array-utils";
import dashboardPageStore from "../../store/DashboardPageStore";
import {observerDashboardPageWrapper} from "./ObserverDashboardPageWrapper";
import {getMarketAccountsByMarketId, MarketAccountResponse} from "../../apis/MarketAccountApi";
import LazyTabs from "../LazyTabs";
import MarketAccountMonthDocumentDetailPage from "../MarketAccountMonthDocumentDetailPage";
import {useLocation} from "react-router-dom";


export interface pageProps {
    marketId: string
    year: string
    month: string
    accountId: string
}

const myPath = "markets/{marketId}/saleDocuments/{year}/{month}"

const MarketMonthSaleDocumentDetailPage: React.FC<pageProps> = (props) => {
    const [accounts, setAccounts] = useState<MarketAccountResponse[]>([])
    let marketId = Number(props.marketId)
    let month = Number(props.month);
    let year = Number(props.year);
    let location = useLocation();
    useEffect(() => {
        getMarketAccountsByMarketId(marketId).then(res => {
            setAccounts(res.data)
        })
    }, [marketId]);
    const [details, setDetails] = useState<MarketSaleDocumentDetail[]>([])
    useEffect(() => {
        if (details.length) {
            let first = details[0];
            let path = myPath.replace("{marketId}", marketId.toString())
                .replace("{year}", year.toString())
                .replace("{month}", month.toString()) + location.search;
            dashboardPageStore.setTitle(path, `${first.market.name}${year}年${month}月销售单`)
        }
    }, [details, location]);

    async function query(accountId: number) {
        try {
            let response = await getMarketSaleDocumentDetailByMonth(accountId, year, month);
            ArrayUtils.removeBy(details, d => d.id === response.data.id)
            details.push(response.data)
            setDetails(Array.from(details))
            return response
        } catch (e) {

        }
    }

    return (
        <>
            {!!accounts.length&&<LazyTabs defaultActiveKey={props.accountId} lazyItems={accounts.map(account => {
                return {
                    key: account.id.toString(),
                    label: account.name,
                    render: () => {
                        let detail = details.find(it => it.account.id === account.id);
                        return <MarketAccountMonthDocumentDetailPage key={`${year}-${month}`} accountId={account.id}
                                                                     marketId={marketId}
                                                                     month={month} data={detail}
                                                                     onMove={async (goodsIds, targetAccount) => {
                                                                         let targetAccountDocumentDetail = details.find(it => it.account.id === targetAccount);

                                                                         if (!targetAccountDocumentDetail) {
                                                                             await createMarketSaleDocument(targetAccount, {
                                                                                 year: year,
                                                                                 month: month,
                                                                             })
                                                                         }

                                                                         await moveItemsToAnotherDocument(account.id, year, month, {
                                                                             targetAccountId: targetAccount,
                                                                             goodsIds,
                                                                         })
                                                                         let sourceDetail = details.find(detail => detail.account.id === account.id);
                                                                         let movedItems = sourceDetail?.items.filter(it => goodsIds.includes(it.id)) ?? []
                                                                         if (sourceDetail) {
                                                                             sourceDetail.items.filter(it => goodsIds.includes(it.id))
                                                                             let myItems = sourceDetail.items.filter(it => !goodsIds.some(item => it.id === item));
                                                                             sourceDetail.items = myItems
                                                                         }

                                                                         if (targetAccountDocumentDetail?.items) {
                                                                             targetAccountDocumentDetail.items = targetAccountDocumentDetail?.items.concat(movedItems.map(item => {
                                                                                 return {
                                                                                     ...item,
                                                                                 }
                                                                             }))
                                                                         }
                                                                         setDetails(Array.from(details))
                                                                         if (!targetAccountDocumentDetail) {
                                                                             setTimeout(() => {
                                                                                 query(targetAccount)
                                                                             }, 300)
                                                                         }
                                                                     }}
                                                                     accounts={accounts}
                                                                     onChange={data => {
                                                                         let index = details.findIndex(detail => detail.account.id === account.id);
                                                                         details[index] = data
                                                                         setDetails(Array.from(details))
                                                                     }} onQuery={async () => {
                            await query(account.id)
                        }} year={year}/>
                    }
                }
            })}/>}
        </>
    )
}

export default observerDashboardPageWrapper(MarketMonthSaleDocumentDetailPage, myPath, "卖场销售详情")

